//
//  WalletController.swift
//  SCA
//
//  Created by tjun on 2025/9/1.
//

import UIKit

class WalletController: BaseController {
    
    private var header = WalletHeaderView(frame: CGRectMake(0, 0, screenWidth, 160))
    private var walletInfo: WalletInfo?
    private var coinModels: [WalletCoinModel] = []
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = AppStyle.color.background
        tableView.rowHeight = 75
        tableView.contentInsetAdjustmentBehavior = .never;
        tableView.register(WalletCoinListCell.self, forCellReuseIdentifier: WalletCoinListCell.identifier)
        tableView.estimatedRowHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.estimatedSectionHeaderHeight = 0
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setNavigationBarUI()
        
        header.onActionButtonTapped = {[weak self] actionType in
            self?.actionButtonTapped(type: actionType)
        }
        
        tableView.tableHeaderView = header
        tableView.separatorStyle = .singleLine
        tableView.separatorColor = UIColorMake(0xAFB2B7).withAlphaComponent(0.5)
        tableView.separatorInset = .zero
        tableView.addTo(view)
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(navBarHeight)
        }
        
        reloadHeaderData()
        
        NotificationCenter.default.addObserver(self, selector: #selector(loadData), name: NotificationName.transactionSuccess, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(loadData), name: NotificationName.swapSuccess, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(reloadHeaderData), name: NotificationName.pin2faStateChange, object: nil)
        
        loadData()
        
        header.tipSet2FAView.addTapGesturesWithTarget(target: self, action: #selector(tipSet2FAViewTapped))
        header.tipSetPinView.addTapGesturesWithTarget(target: self, action: #selector(tipSetPinViewTapped))
    }
    
    @objc func tipSet2FAViewTapped() {
        let validatorBindingController = ValidatorBindingController()
        navigationController?.pushViewController(validatorBindingController, animated: true)
    }
    
    @objc func tipSetPinViewTapped() {
        let validatorBindingController = ModifySecondaryPasswordController()
        navigationController?.pushViewController(validatorBindingController, animated: true)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    private func actionButtonTapped(type: ActionButtonType) {
        if type == .transfer {
            var transactionModel: WalletCoinModel?
            if let usdcModel = coinModels.first(where: { $0.coinName.lowercased() == "usca" }) {
                transactionModel = usdcModel
            } else if let firstModel = coinModels.first {
                transactionModel = firstModel
            }
            
            if let model = transactionModel {
                let transactionController = TransactionController(model: model)
                navigationController?.pushViewController(transactionController, animated: true)
            }
            return
        }
        
        if type == .exchange {
            let swapController = SwapController()
            swapController.walletInfo = walletInfo
            navigationController?.pushViewController(swapController, animated: true)
            return
        }
        
        if type == .withdraw {
            let alert = Alert.alert(title: "温馨提示".localizedString, message: "努力制作中".localizedString, preferredStyle: .alert)
            alert.addAction(title: "Ok") {}.showIn(self)
            return
            let withdrawalController = WithdrawalController()
            navigationController?.pushViewController(withdrawalController, animated: true)
            return
        }
        
        if type == .recharge {
            let rechargeController = RechargeNetworkController()
            navigationController?.pushViewController(rechargeController, animated: true)
            return
        }
        
    }
    
    private func setNavigationBarUI() {
        
        navigationBar.title = nil
        
        let infoButton = UIButton(image: UIImage(named: "nav_mine_info"), target: self, action: #selector(infoButtonTapped))
        navigationBar.contentView.addSubview(infoButton)
        infoButton.snp.makeConstraints { make in
            make.left.equalTo(10)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(40)
        }
        
        let logoImageView = UIImageView(image: UIImage(named: "nav_logo"))
        navigationBar.contentView.addSubview(logoImageView)
        logoImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
        
        let logoutButton = UIButton(image: UIImage(named: "nav_logout"), target: self, action: #selector(logoutButtonTapped))
        navigationBar.contentView.addSubview(logoutButton)
        logoutButton.snp.makeConstraints { make in
            make.right.equalTo(-10)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(40)
        }
        
    }
    
    @objc func infoButtonTapped() {
        let mineController = MineController()
        mineController.showInController(self)
    }
    
    @objc func logoutButtonTapped() {
        NotificationCenter.default.post(name: NotificationName.userLogout, object: nil)
    }
    
    @objc func reloadHeaderData() {
        
        header.reloadData()
        header.setNeedsLayout()
        header.layoutIfNeeded()
        
        if let headerLastView = header.lastView {
            header.frame = CGRectMake(0, 0, screenWidth, headerLastView.maxY + 16)
        }
    }
    
    @objc func loadData() {
        WalletService.loadWalletInfo(success: {walletInfo in
            self.walletInfo = walletInfo
            self.header.walletInfo = walletInfo
            self.coinModels = walletInfo.coinModels
            self.tableView.reloadData()
        })
    }
}


extension WalletController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return coinModels.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: WalletCoinListCell.identifier, for: indexPath) as! WalletCoinListCell
        let model = coinModels[indexPath.row]
        cell.model = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let model = coinModels[indexPath.row]
        let detailController = WalletDetailController(coinModel: model)
        navigationController?.pushViewController(detailController, animated: true)
    }
    
}
